package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.driver.client.CiFeignClient;
import com.atguigu.daijia.driver.service.FileService;
import com.atguigu.daijia.driver.service.MonitorService;
import com.atguigu.daijia.model.entity.order.OrderMonitor;
import com.atguigu.daijia.model.entity.order.OrderMonitorRecord;
import com.atguigu.daijia.model.form.order.OrderMonitorForm;
import com.atguigu.daijia.model.vo.order.TextAuditingVo;
import com.atguigu.daijia.order.client.OrderMonitorFeignClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class MonitorServiceImpl implements MonitorService {

    private final FileService fileService;
    private final OrderMonitorFeignClient orderMonitorFeignClient;
    private final CiFeignClient ciFeignClient;


    /**
     * 保存订单监控记录
     * @param file
     * @param orderMonitorForm
     * @return
     */
    @Override
    public Boolean saveOrderMonitorRecord(MultipartFile file, OrderMonitorForm orderMonitorForm) {
        // 上传代驾期间的监控音频到 MinIO
        String url = fileService.uploadToMinIO(file);

        // 将代驾期间的监控音频的文本内容保存到 MongoDB
        OrderMonitorRecord orderMonitorRecord = new OrderMonitorRecord();
        orderMonitorRecord.setOrderId(orderMonitorForm.getOrderId());
        orderMonitorRecord.setFileUrl(url);
        orderMonitorRecord.setContent(orderMonitorForm.getContent());
        // 远程调用 service-driver 模块文本内容审核接口，审核文本内容
        TextAuditingVo textAuditingVo = ciFeignClient.textAuditing(orderMonitorForm.getContent()).getData();
        // 设置文本内容审核结果
        orderMonitorRecord.setResult(textAuditingVo.getResult());
        // 设置审核得到的文本内容风险关键词
        orderMonitorRecord.setKeywords(textAuditingVo.getKeywords());
        // 远程调用 service-order 模块保存订单监控记录
        orderMonitorFeignClient.saveOrderMonitorRecord(orderMonitorRecord);

        // 更新数据库中的订单监控统计记录
        OrderMonitor orderMonitor = orderMonitorFeignClient.getOrderMonitorByOrderId(orderMonitorForm.getOrderId()).getData();
        if (StringUtils.hasText(url)) {
            // 代驾期间的监控音频成功上传到 MinIO，文件个数加一
            int fileNum = orderMonitor.getFileNum() + 1;
            orderMonitor.setFileNum(fileNum);
        }
        if ("2".equals(orderMonitorRecord.getResult())) {
            // 审核结果: 0（审核正常），1 （判定为违规敏感文件），2（疑似敏感，建议人工复核）
            // 文本内容审核结果为疑似敏感，建议人工复核，审核次数加一
            int auditNum = orderMonitor.getAuditNum() + 1;
            orderMonitor.setAuditNum(auditNum);
        }
        orderMonitorFeignClient.updateOrderMonitor(orderMonitor);
        return true;
    }
}
